import {
    FC, ReactNode, useCallback, useRef, useEffect
} from 'react';
import { initShader } from '@utils/utils';
import styles from './template.module.less';

export interface TemplateProps {
    children?: ReactNode;
}

const Template: FC<TemplateProps> = () => {
    const canvasRef = useRef(null);

    const main = useCallback(async (canvas: HTMLCanvasElement) => {
        const gl = canvas.getContext('webgl');

        const VERTEX_SHADER_SOURCE = `
            attribute vec4 aPosition;
            void main() {
                gl_Position = aPosition;
                gl_PointSize = 10.0;
            }
        `;

        const FRAGMENT_SHADER_SOURCE = `
            void main() {
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
            }
        `;

        const program = initShader(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);

        const aPosition = gl.getAttribLocation(program, 'aPosition');

        const points = new Float32Array([
            -0.5, -0.5,
            0.5, -0.5,
            -0.5, 0.5,
            0.5, 0.5
        ]);

        const pointsBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, pointsBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);

        gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0);
        gl.enableVertexAttribArray(aPosition);
        gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
        return () => {
            console.log('remove');
        };
    }, []);

    useEffect(() => {
        let removeEvent = null;
        if (canvasRef.current) {
            removeEvent = main(canvasRef.current);
        }

        return () => {
            if (typeof removeEvent === 'function') {
                removeEvent?.();
            }
        };
    }, [main]);

    return (
        <div className={styles.template}>
            <canvas ref={canvasRef} width="600" height="400" />
        </div>
    );
};

export default Template;
